<?php
namespace app\ask\controller;

use think\Controller;

class Post extends Controller
{
    //关联查询的意思
    protected $relationSearch = true;
    public function __construct()
    {
        parent::__construct();
        $this->PostModel=model("Post.Post");
        $this->CateModel=model("Post.Category");
        $this->BusinessModel=model("Business.Business");
        $this->CommentModel=model("Post.Comment");
    }
    public function index()
    {
        if($this->request->isPost())
        {
            $cateid = $this->request->param('cateid', 0, 'trim');
            $keywords = $this->request->param('keywords', '', 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit=5;
            $start=($page-1)*$limit;
            $where=[];

            if($cateid)
            {
                $where['cateid'] = $cateid;
            }

            if(!empty($keywords))
            {
                $where['title'] = ['LIKE',"%$keywords%"];
            }
            $list=$this->PostModel->with(['business','category'])->where($where)->order('post.createtime','desc')->limit($start,$limit)->select();
            if($list)
            {
                $this->success('查询帖子成功',null,$list);
                exit;
            }else
            {
                $this->error('暂无更多数据');
                exit;
            }
        }
    }

    // 发布问题
    public function add()
    {
        if($this->request->isPost())
        {
            $busid = $this->request->param('busid', 0, 'trim');
            $point = $this->request->param('point', 0, 'trim');

            // 查询用户是否存在
            $business=$this->BusinessModel->find($busid);
            if(!$business)
            {
                $this->error("用户不存在");
                exit;
            }

            // 发帖逻辑
            $money=$business['money'];
            // 用余额减去积分
            $update=bcsub($money,$point);
            if($update<0)
            {
                $this->error("积分余额不足");
                exit;
            }

            // 发帖涉及 帖子表 post 插入
            // 客户表 business 余额更新
            // 消费记录表 business_record 插入

            // 加载模型
            $PostModel=model('Post.Post');
            $BusinessModel=model('Business.Business');
            $RecordModel=model('Business.Record');

            // 开启事务
            $PostModel->startTrans();
            $BusinessModel->startTrans();
            $RecordModel->startTrans();

            // 帖子表数据
            $PostData=[
                'title' => $this->request->param('title', '', 'trim'),
                'content' => $this->request->param('content', '', 'trim'),
                'point' => $point,
                'busid' => $busid,
                'cateid' => $this->request->param('cateid', '', 'trim'),
                'status' => '0',
            ];
            $PostStatus=$PostModel->validate('common/Post/Post')->save($PostData);
            if($PostStatus===FALSE)
            {
                $this->error($PostModel->getError());
                exit;
            }

            // 客户表更新数据
            $BusinessData=[
                'id'=>$busid,
                'money'=>$update,
            ];

            //验证器
            $validate = [
                [
                    'money' => ['number', '>=:0'],
                ],
                [
                    'money.number'      => '余额必须是数字类型',
                    'money.>='      => '余额必须大于等于0元',
                ]
            ];
            $BusinessStatus=$BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);
            if($BusinessStatus===FALSE)
            {
                $PostModel->rollback();
                $this->error($BusinessModel->getError());
                exit;
            }

            // 消费记录表插入数据
            $content = "在知识问答社区发帖花费 ￥$point 元";
            $RecordData = [
                'total' => "-$point",
                'busid' => $busid,
                'content' => $content
            ];

            $RecordStatus=$RecordModel->validate('common/Business/Record')->save($RecordData);
            if($RecordStatus===FALSE)
            {
                $BusinessModel->rollback();
                $PostModel->rollback();
                $this->error($RecordModel->getError());
                exit;
            }

            if($PostStatus===FALSE || $BusinessStatus===FALSE || $RecordStatus===FALSE)
            {
                $RecordModel->rollback();
                $BusinessModel->rollback();
                $PostModel->rollback();
                $this->error("发布问题失败，请重新操作");
                exit;
            }else
            {
                $PostModel->commit();
                $BusinessModel->commit();
                $RecordModel->commit();
                $this->success('发布提问成功，请等待回答', '/pages/post/info', ['postid' => $PostModel->id]);
                exit;
            }

        }
    }

    public function cate()
    {
        if($this->request->isPost())
        {
            $list=$this->CateModel->select();
            if($list)
            {
                $this->success('查询分类成功',null,$list);
                exit;
            }else
            {
                $this->error('暂无分类数据');
                exit;
            }
        }
    }

    // 帖子详情
    public function info()
    {
        if($this->request->isPost())
        {
            $postid=$this->request->param('postid',0,'trim');
            
            $post=$this->PostModel->with(['category','business'])->find($postid);

            $where = [
                'postid' => $postid,
                'busid' => ['NOT NULL', '']
            ];
            // $comment=$this->CommentModel->with(['business'])->where($where)->select();
            // $person=$this->CommentModel->where($where)->count();
            // $post['person']=$person;
            // $list=[
            //     'post'=>$post,
            //     'comment'=>$comment
            // ];
            if($post)
            {
                $this->success('查询帖子详情成功',null,$post);
                exit;
            }
        }
    }

    // 帖子编辑
    public function edit()
    {
        $busid = $this->request->param('busid', 0, 'trim');
        $postid = $this->request->param('id', 0, 'trim');
        $params=$this->request->param();
        // halt($postid);
        // exit;

        // 查询用户是否存在
        $business=$this->BusinessModel->find($busid);
        if(!$business)
        {
            $this->error("用户不存在");
            exit;
        }

        // 查询帖子是否存在
        $post=$this->PostModel->find($postid);
        if(!$post)
        {
            $this->error("帖子不存在");
            exit;
        }

        // 修改帖子的金额
        $point=$post['point'];
        $money=$business['money'];
        $UpdatePoint=0;
        $UpdateMoney=0;
        if($point != $params['point'])
        {
            if($params['point']<$point )
            {
                // $UpdatePoint=bcsub($point,$params['point']);
                // $UpdateMoney=bcadd($money,$UpdatePoint);
                $this->error('悬赏积分更改不能少于上一次');
                exit;
            }else{
                $UpdatePoint=bcsub($params['point'],$point);
                $UpdateMoney=bcsub($money,$UpdatePoint);
                if($UpdateMoney<0)
                {
                    $this->error('积分余额不足');
                    exit;
                }
            }
        }else
        {
            $UpdateMoney=$money;
        }
        // halt($UpdatePoint);
        // exit;
        // 修改帖子 帖子表 更新
        // 客户表 余额改变
        // 消费记录表 插入

        // 加载模型
        $PostModel=model('Post.Post');
        $BusinessModel=model('Business.Business');
        $RecordModel=model('Business.Record');

        // 开启事务
        $PostModel->startTrans();
        $BusinessModel->startTrans();
        $RecordModel->startTrans();

        //帖子表
        $PostData = [
            'id'=>$postid,
            'title' => $this->request->param('title', '', 'trim'),
            'content' => $this->request->param('content', '', 'trim'),
            'point' => $this->request->param('point', '', 'trim'),
            'busid' => $busid,
            'cateid' => $this->request->param('cateid', '', 'trim'),
            'status' => '0',
        ];

        $PostStatus = $PostModel->validate('common/Post/Post')->isUpdate(true)->save($PostData);
        if($PostStatus === FALSE)
        {
            $this->error($PostModel->getError());
            exit;
        }

        //更新用户余额
        $BusinessData = [
            'id' => $busid,
            'money' => $UpdateMoney
        ];

        //验证器
        $validate = [
            [
                'money' => ['number', '>=:0'],
            ],
            [
                'money.number'      => '余额必须是数字类型',
                'money.>='      => '余额必须大于等于0元',
            ]
        ];

        $BusinessStatus = $BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

        if($BusinessStatus === FALSE)
        {
            $PostModel->rollback();
            $this->error($BusinessModel->getError());
            exit;
        }

        //消费记录表
        if($UpdatePoint>0)
        {
            $content = "在知识问答社区发帖花费 ￥$UpdatePoint 元";
            $RecordData = [
                'total' => "-$UpdatePoint",
                'busid' => $busid,
                'content' => $content
            ];
            $RecordStatus = $RecordModel->validate('common/Business/Record')->save($RecordData);
            if($RecordStatus === FALSE)
            {
                $BusinessModel->rollback();
                $PostModel->rollback();
                $this->error($RecordModel->getError());
                exit;
            }
            if($PostStatus === FALSE || $BusinessStatus === FALSE || $RecordStatus === FALSE)
            {
                $RecordModel->rollback();
                $BusinessModel->rollback();
                $PostModel->rollback();
                $this->error("修改提问失败，请重新操作");
                exit;
            }else
            {
                $PostModel->commit();
                $BusinessModel->commit();
                $RecordModel->commit();
                $this->success('修改提问成功，请等待回答', '/pages/post/info', ['postid' => $PostModel->id]);
                exit;
            }
        }else
        {
            if($PostStatus === FALSE || $BusinessStatus === FALSE)
            {
                $BusinessModel->rollback();
                $PostModel->rollback();
                $this->error("修改提问失败，请重新操作");
                exit;
            }else
            {
                $PostModel->commit();
                $BusinessModel->commit();
                $RecordModel->commit();
                $this->success('修改提问成功，请等待回答', '/pages/post/info', ['postid' => $PostModel->id]);
                exit;
            }
        }

        
        
    }

    public function del()
    {
        if($this->request->isPost())
        {
            $postid=$this->request->param("postid",0,'trim');
            // halt($postid);
            $post=$this->PostModel->get($postid);
            if(!$post)
            {
                $this->error('帖子不存在');
                exit;
            }
            $result=$post->delete();
            if($result===false)
            {
                $this->error('帖子删除失败');
                exit;
            }
            $this->success('帖子删除成功');
            exit;
        }
    }
}